package org.cypress.rtpack.common.utils;

import java.io.InputStream;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * @author vv
 * @since 2021-02-22
 */
public class JaxbReadXml {

    @SuppressWarnings("unchecked")
    public static <T> T unmarshal(Class<T> clazz, String path) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(clazz);
        Unmarshaller u = jc.createUnmarshaller();
        InputStream dataStream = JaxbReadXml.class.getClassLoader().getResourceAsStream(path);
        return (T) u.unmarshal(dataStream);
    }

    public static <T> String marshal(Class<T> clazz, T ins) throws JAXBException{
        JAXBContext context = JAXBContext.newInstance(clazz);
        Marshaller mar = context.createMarshaller();
        mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        StringWriter writer = new StringWriter();
        mar.marshal(ins, writer);
        return writer.toString();
    }



}
